package com.epam.web_project.bank.command.admin_commands;

import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Date;
import java.util.Locale;
import java.util.ResourceBundle;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.epam.web_project.bank.command.Command;
import com.epam.web_project.bank.dao.account_dao.AccountDAO;
import com.epam.web_project.bank.dao.factory.MySQLDAOFactory;
import com.epam.web_project.bank.db.ConnectionPool;
import com.epam.web_project.bank.entity.Account;
import com.epam.web_project.bank.entity.Card;
import com.epam.web_project.bank.entity.Currency;
import com.epam.web_project.bank.exception.CreateAccountException;
import com.epam.web_project.bank.util.AppPropertiesLoader;
import com.epam.web_project.bank.util.CurrencyStringConverter;

public class CreateAccountCommand implements Command {

	private static Logger logger=Logger.getLogger(CreateAccountCommand.class);
	//admin "creates and approves an account" (updates the account and the card)
	@Override
	public String execute(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String resPage=null;
		AppPropertiesLoader props=AppPropertiesLoader.getInstance();
		Account account=new Account();
		Card card=new Card();
		account.setId(Integer.valueOf(request.getParameter("accId")));
		account.setAmount(new BigDecimal(request.getParameter("amount")));
		account.setBlocked(Boolean.valueOf(request.getParameter("blocked")));
		account.setCreditLimit(new BigDecimal(request.getParameter("limit")));
		Currency currency=CurrencyStringConverter.convertToCurrency(request.getParameter("currency"));
		account.setCurrency(currency);
		account.setIban(request.getParameter("iban"));
		card.setCardType(request.getParameter("type"));
		card.setCvv(request.getParameter("cvv"));
		card.setExpires(Date.valueOf(request.getParameter("expires")));
		card.setNumber(request.getParameter("cardNum"));
		account.setCard(card);
		MySQLDAOFactory daoFactory = new MySQLDAOFactory();
		daoFactory.setConnectionPool(ConnectionPool.getInstance());
		AccountDAO accountDAO=daoFactory.getAccountDAO();
		HttpSession session = request.getSession();
		Locale locale=request.getLocale();
		ResourceBundle bundle=ResourceBundle.getBundle("i18n", locale);
		if(accountDAO.update(account)) {
			resPage=props.getProperty("show_admin_main_command");
			session.setAttribute("message", bundle.getString("java.acc_appr"));
		} else {
			logger.warn(props.getProperty("CREATE_ACCOUNT_FAIL"));
			throw new CreateAccountException(props.getProperty("CREATE_ACCOUNT_FAIL"));
		}
		return resPage;
	}

}
